package com.delicious.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.delicious.dao.impl.CategoryDaoImpl;
import com.delicious.dao.impl.FoodsDaoImpl;
import com.delicious.entity.Category;
import com.delicious.entity.Foods;

public class ProductListServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Category> clist = new CategoryDaoImpl().getList();
		int cid = 0;
		if(request.getParameter("cid")!=null && !request.getParameter("cid").isEmpty())
			cid = Integer.parseInt(request.getParameter("cid"));
		String name = "";
		if(request.getParameter("name")!=null && !request.getParameter("name").isEmpty()){
			name = request.getParameter("name");
		}
		System.out.println(name);
		int pageSize = 8;
		int pageNum = 1;
		if(request.getParameter("pageNum") != null && !request.getParameter("pageNum").isEmpty())
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
		int rows = new FoodsDaoImpl().getFoodsByNameAndCid(0, 0, name, cid).size();
		int totalPage = (int)Math.ceil((double)rows/pageSize);
		
		List<Foods> flist = new FoodsDaoImpl().getFoodsByNameAndCid(pageNum, pageSize, name, cid);
		
		request.setAttribute("foods", flist);
		request.setAttribute("clist", clist);
		request.setAttribute("name", name);
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("totalPage", totalPage);
		
		request.getRequestDispatcher("productList.jsp").forward(request, response);
	}
	
	public static void main(String[] args) {
		for(Foods f : new FoodsDaoImpl().getFoodsByNameAndCid(0, 0, null, 0)){
			System.out.println(f.getChineseName()+"\t"+f.getId());
		}
	}

}
